package com.kds.fxtool.service;

import com.kds.fxtool.domain.MenuItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class MenuService {
    private static final Logger logger = LoggerFactory.getLogger(MenuService.class);

    // 配置常量
    private static final String MENU_API_URL = "http://localhost:8080/api/menu/tree"; // 树形结构API
    private static final long CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存
    private static final int REQUEST_TIMEOUT_SECONDS = 10; // 请求超时时间

    // 缓存相关
    private List<MenuItem> cachedMenu;
    private long lastLoadTime;
    private boolean cacheEnabled = true;

    // HTTP客户端（单例）
//    private final HttpClient httpClient;

    public MenuService() {
//        this.httpClient = HttpClient.newBuilder()
//                .connectTimeout(Duration.ofSeconds(REQUEST_TIMEOUT_SECONDS))
//                .build();
    }

    /**
     * 加载菜单树（支持缓存）
     */
    public List<MenuItem> loadMenuTree() {
        // 如果缓存有效且未过期，使用缓存
        if (cacheEnabled && cachedMenu != null &&
                System.currentTimeMillis() - lastLoadTime < CACHE_DURATION) {
            logger.debug("使用缓存菜单数据");
            return deepCopyMenuTree(cachedMenu);
        }

        try {
            List<MenuItem> menuData = loadMenuTreeFromApi();
            if (menuData != null && !menuData.isEmpty()) {
                cachedMenu = deepCopyMenuTree(menuData);
                lastLoadTime = System.currentTimeMillis();
                logger.info("成功从API加载菜单，共 {} 个菜单组", menuData.size());
                return menuData;
            } else {
                logger.warn("API返回空菜单数据，使用默认菜单");
                return getDefaultMenuTree();
            }
        } catch (Exception e) {
            logger.error("从API加载菜单失败，使用默认菜单", e);
            return getDefaultMenuTree();
        }
    }

    /**
     * 从API异步加载菜单树
     */
    public CompletableFuture<List<MenuItem>> loadMenuTreeAsync() {
        return CompletableFuture.supplyAsync(() -> {
            try {
                return loadMenuTree();
            } catch (Exception e) {
                logger.error("异步加载菜单失败", e);
                return getDefaultMenuTree();
            }
        });
    }

    /**
     * 从API加载菜单树
     */
    private List<MenuItem> loadMenuTreeFromApi() throws Exception {
        logger.info("开始从API加载菜单: {}", MENU_API_URL);

//        HttpRequest request = HttpRequest.newBuilder()
//                .uri(URI.create(MENU_API_URL))
//                .header("Content-Type", "application/json")
//                .header("Accept", "application/json")
//                .header("User-Agent", "ManagementSystem/1.0")
//                .timeout(Duration.ofSeconds(REQUEST_TIMEOUT_SECONDS))
//                .GET()
//                .build();
//
//        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
//
//        logger.debug("菜单API响应状态码: {}", response.statusCode());
//
//        if (response.statusCode() == 200) {
//            String responseBody = response.body();
//            if (responseBody == null || responseBody.trim().isEmpty()) {
//                throw new RuntimeException("API返回空响应");
//            }
//
//            ObjectMapper mapper = new ObjectMapper();
//            List<MenuItem> menuTree = mapper.readValue(responseBody, new TypeReference<List<MenuItem>>() {});

//            // 验证并处理菜单数据
//            return validateAndProcessMenuTree(menuTree);
//
//        } else if (response.statusCode() == 404) {
//            logger.warn("菜单API不存在 (404)，使用默认菜单");
//            return getDefaultMenuTree();
//        } else if (response.statusCode() >= 500) {
//            logger.error("菜单API服务器错误 ({})，使用默认菜单", response.statusCode());
//            return getDefaultMenuTree();
//        } else {
//            throw new RuntimeException("菜单API请求失败，状态码: " + response.statusCode());
//        }
        return getDefaultMenuTree();
    }

    /**
     * 验证和处理菜单树
     */
    private List<MenuItem> validateAndProcessMenuTree(List<MenuItem> menuTree) {
        if (menuTree == null || menuTree.isEmpty()) {
            return menuTree;
        }

        List<MenuItem> validMenuTree = new ArrayList<>();

        for (MenuItem item : menuTree) {
            MenuItem validatedItem = validateMenuItem(item);
            if (validatedItem != null) {
                validMenuTree.add(validatedItem);
            }
        }

        // 排序菜单树
        sortMenuTree(validMenuTree);

        logger.debug("菜单树验证完成，有效菜单组: {}", validMenuTree.size());
        return validMenuTree;
    }

    /**
     * 验证菜单项
     */
    private MenuItem validateMenuItem(MenuItem menuItem) {
        if (menuItem == null) {
            return null;
        }

        // 基本验证
        if (menuItem.getId() == null || menuItem.getId().trim().isEmpty()) {
            logger.warn("发现ID为空的菜单项，已跳过: {}", menuItem.getTitle());
            return null;
        }

        if (menuItem.getTitle() == null || menuItem.getTitle().trim().isEmpty()) {
            logger.warn("发现标题为空的菜单项，已跳过: {}", menuItem.getId());
            return null;
        }

        // 设置默认值
        if (menuItem.getType() == null) {
            menuItem.setType("page"); // 默认为页面类型
        }

        if (menuItem.getSortOrder() == 0) {
            menuItem.setSortOrder(999); // 默认排序值
        }

        // 递归验证子项
        if (menuItem.getChildren() != null && !menuItem.getChildren().isEmpty()) {
            List<MenuItem> validChildren = new ArrayList<>();
            for (MenuItem child : menuItem.getChildren()) {
                MenuItem validatedChild = validateMenuItem(child);
                if (validatedChild != null) {
                    validChildren.add(validatedChild);
                }
            }
            menuItem.setChildren(validChildren);
        }

        return menuItem;
    }

    /**
     * 获取默认菜单树（API不可用时的备用数据）
     */
    public List<MenuItem> getDefaultMenuTree() {
        logger.info("使用默认菜单树");

        List<MenuItem> menuTree = new ArrayList<>();

        // 首页菜单组
        MenuItem homeGroup = new MenuItem("home", "🏠 首页", "🏠", "group");
        homeGroup.setExpanded(true);
        homeGroup.setSortOrder(1);

        MenuItem dashboard = new MenuItem("dashboard", "控制台", "", "page");
        dashboard.setFxmlFile("home-page.fxml");
        dashboard.setAction("navigateToHome");
        dashboard.setSortOrder(1);
        homeGroup.addChild(dashboard);

        MenuItem workspace = new MenuItem("workspace", "工作台", "", "page");
        workspace.setAction("navigateToWorkspace");
        workspace.setSortOrder(2);
        homeGroup.addChild(workspace);

        menuTree.add(homeGroup);

        // 用户管理菜单组
        MenuItem userGroup = new MenuItem("user", "👥 用户管理", "👥", "group");
        userGroup.setSortOrder(2);

        MenuItem userList = new MenuItem("userList", "用户列表", "", "page");
        userList.setFxmlFile("user-list.fxml");
        userList.setAction("navigateToUserList");
        userList.setSortOrder(1);
        userGroup.addChild(userList);

        MenuItem addUser = new MenuItem("addUser", "新增用户", "", "page");
        addUser.setFxmlFile("add-user.fxml");
        addUser.setAction("navigateToAddUser");
        addUser.setSortOrder(2);
        userGroup.addChild(addUser);

        MenuItem userRoles = new MenuItem("userRoles", "角色配置", "", "page");
        userRoles.setAction("navigateToUserRoles");
        userRoles.setSortOrder(3);
        userGroup.addChild(userRoles);

        menuTree.add(userGroup);

        // 订单管理菜单组
        MenuItem orderGroup = new MenuItem("order", "📦 订单管理", "📦", "group");
        orderGroup.setSortOrder(3);

        MenuItem orderList = new MenuItem("orderList", "订单列表", "", "page");
        orderList.setAction("navigateToOrderList");
        orderList.setSortOrder(1);
        orderGroup.addChild(orderList);

        MenuItem orderAnalysis = new MenuItem("orderAnalysis", "订单分析", "", "page");
        orderAnalysis.setAction("navigateToOrderAnalysis");
        orderAnalysis.setSortOrder(2);
        orderGroup.addChild(orderAnalysis);

        menuTree.add(orderGroup);

        // 数据统计菜单组
        MenuItem statsGroup = new MenuItem("stats", "📊 数据统计", "📊", "group");
        statsGroup.setSortOrder(4);

        MenuItem statistics = new MenuItem("statistics", "数据概览", "", "page");
        statistics.setAction("navigateToStatistics");
        statistics.setSortOrder(1);
        statsGroup.addChild(statistics);

        MenuItem reports = new MenuItem("reports", "报表分析", "", "page");
        reports.setAction("navigateToReports");
        reports.setSortOrder(2);
        statsGroup.addChild(reports);

        menuTree.add(statsGroup);

        // 系统设置菜单组
        MenuItem systemGroup = new MenuItem("system", "⚙️ 系统设置", "⚙️", "group");
        systemGroup.setSortOrder(5);

        MenuItem systemConfig = new MenuItem("systemConfig", "系统配置", "", "page");
        systemConfig.setAction("navigateToSystemConfig");
        systemConfig.setSortOrder(1);
        systemGroup.addChild(systemConfig);

        MenuItem logManagement = new MenuItem("logManagement", "日志管理", "", "page");
        logManagement.setAction("navigateToLogManagement");
        logManagement.setSortOrder(2);
        systemGroup.addChild(logManagement);

        menuTree.add(systemGroup);

        // 按排序号排序
        sortMenuTree(menuTree);

        return menuTree;
    }

    /**
     * 递归排序菜单树
     */
    private void sortMenuTree(List<MenuItem> menuItems) {
        if (menuItems == null || menuItems.isEmpty()) {
            return;
        }

        // 排序当前层级
        menuItems.sort(Comparator.comparingInt(MenuItem::getSortOrder));

        // 递归排序子层级
        for (MenuItem item : menuItems) {
            if (!item.isLeaf()) {
                sortMenuTree(item.getChildren());
            }
        }
    }

    /**
     * 获取快速操作菜单树
     */
    public List<MenuItem> getQuickActionsTree() {
        List<MenuItem> quickActions = new ArrayList<>();

        MenuItem refresh = new MenuItem("refresh", "🔄 刷新缓存", "🔄", "action");
        refresh.setSortOrder(1);
        quickActions.add(refresh);

        MenuItem export = new MenuItem("export", "📤 数据导出", "📤", "action");
        export.setSortOrder(2);
        quickActions.add(export);

        MenuItem help = new MenuItem("help", "❓ 帮助文档", "❓", "action");
        help.setSortOrder(3);
        quickActions.add(help);

        // 排序
        quickActions.sort(Comparator.comparingInt(MenuItem::getSortOrder));

        return quickActions;
    }

    /**
     * 根据用户权限过滤菜单树
     */
    public List<MenuItem> filterMenuByPermission(List<MenuItem> menuTree, List<String> userPermissions) {
        if (userPermissions == null || userPermissions.isEmpty()) {
            logger.warn("用户权限列表为空，返回原始菜单");
            return menuTree;
        }

        logger.info("根据用户权限过滤菜单，用户权限数: {}", userPermissions.size());

        List<MenuItem> filteredMenu = new ArrayList<>();

        for (MenuItem item : menuTree) {
            MenuItem filteredItem = filterMenuItem(item, userPermissions);
            if (filteredItem != null) {
                filteredMenu.add(filteredItem);
            }
        }

        logger.info("菜单权限过滤完成，原始菜单组: {}，过滤后: {}", menuTree.size(), filteredMenu.size());
        return filteredMenu;
    }

    /**
     * 递归过滤菜单项
     */
    private MenuItem filterMenuItem(MenuItem menuItem, List<String> userPermissions) {
        // 检查当前菜单项是否有权限要求
        if (!hasPermission(menuItem, userPermissions)) {
            return null;
        }

        // 如果是分组，递归过滤子项
        if (!menuItem.isLeaf()) {
            MenuItem clonedItem = cloneMenuItem(menuItem);
            clonedItem.getChildren().clear(); // 清空子项，重新添加

            for (MenuItem child : menuItem.getChildren()) {
                MenuItem filteredChild = filterMenuItem(child, userPermissions);
                if (filteredChild != null) {
                    clonedItem.addChild(filteredChild);
                }
            }

            // 如果分组没有子项，则不显示该分组
            return clonedItem.getChildren().isEmpty() ? null : clonedItem;
        }

        // 叶子节点直接返回
        return cloneMenuItem(menuItem);
    }

    /**
     * 检查菜单项权限
     * 在实际项目中，这里需要根据具体的权限系统实现
     */
    private boolean hasPermission(MenuItem menuItem, List<String> userPermissions) {
        // 这里实现具体的权限检查逻辑
        // 示例实现：假设菜单项的ID就是需要的权限

        // 如果菜单项没有设置权限要求，默认允许访问
        if (menuItem.getId() == null) {
            return true;
        }

        // 检查用户是否拥有该权限
        // 这里可以根据实际需求修改权限检查逻辑
        String requiredPermission = menuItem.getId();

        // 示例：允许所有权限，实际项目中需要根据具体权限系统实现
        return userPermissions.contains(requiredPermission) ||
                userPermissions.contains("admin") || // 管理员拥有所有权限
                isPublicMenu(menuItem); // 公共菜单不需要权限
    }

    /**
     * 判断是否为公共菜单（不需要权限）
     */
    private boolean isPublicMenu(MenuItem menuItem) {
        // 首页通常是公共菜单
        return "home".equals(menuItem.getId()) ||
                "dashboard".equals(menuItem.getId()) ||
                "workspace".equals(menuItem.getId());
    }

    /**
     * 克隆菜单项（深拷贝）
     */
    private MenuItem cloneMenuItem(MenuItem original) {
        if (original == null) {
            return null;
        }

        MenuItem clone = new MenuItem();
        clone.setId(original.getId());
        clone.setTitle(original.getTitle());
        clone.setIcon(original.getIcon());
        clone.setType(original.getType());
        clone.setFxmlFile(original.getFxmlFile());
        clone.setAction(original.getAction());
        clone.setExpanded(original.isExpanded());
        clone.setSortOrder(original.getSortOrder());

        // 递归克隆子项
        if (original.getChildren() != null && !original.getChildren().isEmpty()) {
            for (MenuItem child : original.getChildren()) {
                clone.addChild(cloneMenuItem(child));
            }
        }

        return clone;
    }

    /**
     * 深拷贝菜单树
     */
    private List<MenuItem> deepCopyMenuTree(List<MenuItem> originalTree) {
        List<MenuItem> copy = new ArrayList<>();
        for (MenuItem item : originalTree) {
            copy.add(cloneMenuItem(item));
        }
        return copy;
    }

    /**
     * 强制刷新菜单（清除缓存）
     */
    public void refreshMenu() {
        cachedMenu = null;
        lastLoadTime = 0;
        logger.info("菜单缓存已清除，下次加载将从API重新获取");
    }

    /**
     * 设置缓存是否启用
     */
    public void setCacheEnabled(boolean enabled) {
        this.cacheEnabled = enabled;
        if (!enabled) {
            refreshMenu();
        }
        logger.info("菜单缓存已{}", enabled ? "启用" : "禁用");
    }

    /**
     * 获取缓存状态
     */
    public CacheStatus getCacheStatus() {
        long currentTime = System.currentTimeMillis();
        long timeSinceLastLoad = currentTime - lastLoadTime;
        boolean isCacheValid = cachedMenu != null && timeSinceLastLoad < CACHE_DURATION;

        return new CacheStatus(
                cachedMenu != null,
                isCacheValid,
                lastLoadTime,
                timeSinceLastLoad,
                CACHE_DURATION - timeSinceLastLoad
        );
    }

    /**
     * 搜索菜单项
     */
    public List<MenuItem> searchMenuItems(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return new ArrayList<>();
        }

        List<MenuItem> allMenuItems = loadMenuTree();
        List<MenuItem> results = new ArrayList<>();
        searchInMenuTree(allMenuItems, keyword.toLowerCase(), results);

        logger.debug("菜单搜索完成，关键词: '{}', 结果数: {}", keyword, results.size());
        return results;
    }

    /**
     * 在菜单树中递归搜索
     */
    private void searchInMenuTree(List<MenuItem> menuItems, String keyword, List<MenuItem> results) {
        for (MenuItem item : menuItems) {
            // 检查当前项是否匹配
            if (item.getTitle() != null && item.getTitle().toLowerCase().contains(keyword)) {
                results.add(item);
            }

            // 递归搜索子项
            if (!item.isLeaf()) {
                searchInMenuTree(item.getChildren(), keyword, results);
            }
        }
    }

    /**
     * 根据ID查找菜单项
     */
    public MenuItem findMenuItemById(String id) {
        if (id == null || id.trim().isEmpty()) {
            return null;
        }

        List<MenuItem> allMenuItems = loadMenuTree();
        return findInMenuTree(allMenuItems, id);
    }

    /**
     * 在菜单树中递归查找
     */
    private MenuItem findInMenuTree(List<MenuItem> menuItems, String id) {
        for (MenuItem item : menuItems) {
            if (id.equals(item.getId())) {
                return item;
            }

            if (!item.isLeaf()) {
                MenuItem found = findInMenuTree(item.getChildren(), id);
                if (found != null) {
                    return found;
                }
            }
        }
        return null;
    }

    /**
     * 缓存状态类
     */
    public static class CacheStatus {
        private final boolean hasCache;
        private final boolean isValid;
        private final long lastLoadTime;
        private final long timeSinceLastLoad;
        private final long timeUntilExpire;

        public CacheStatus(boolean hasCache, boolean isValid, long lastLoadTime,
                           long timeSinceLastLoad, long timeUntilExpire) {
            this.hasCache = hasCache;
            this.isValid = isValid;
            this.lastLoadTime = lastLoadTime;
            this.timeSinceLastLoad = timeSinceLastLoad;
            this.timeUntilExpire = timeUntilExpire;
        }

        // Getters
        public boolean hasCache() { return hasCache; }
        public boolean isValid() { return isValid; }
        public long getLastLoadTime() { return lastLoadTime; }
        public long getTimeSinceLastLoad() { return timeSinceLastLoad; }
        public long getTimeUntilExpire() { return timeUntilExpire; }

        @Override
        public String toString() {
            return String.format(
                    "CacheStatus{hasCache=%s, isValid=%s, lastLoadTime=%d, timeSinceLastLoad=%d, timeUntilExpire=%d}",
                    hasCache, isValid, lastLoadTime, timeSinceLastLoad, timeUntilExpire
            );
        }
    }
}